'use client';

import {useEffect, useState} from 'react';
import {SubmitHandler, useForm} from 'react-hook-form';
import FormInput from "@/components/ui/Forms/FormElements/FormInput";
import Button from "@/components/ui/Button/Button";
import {getCaptainData, saveCaptain, updateCaptain} from "@/lib/data";
import {TypeCaptain} from "@/shared/types";
import {useRouter, useSearchParams} from "next/navigation";
import styles from "./CaptainAddPage.module.css";
import CapFerrySkeleton from "@/components/Skeletons/CapFerrySkeleton";
import Image from "next/image";

export default function CaptainForm() {
    const {
        register,
        handleSubmit,
        formState: {errors},
        setValue,
        reset
    } = useForm<TypeCaptain>();
    const {push} = useRouter();

    const [currentImageUrl, setCurrentImageUrl] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    const searchParams = useSearchParams();
    const captainId = searchParams.get('id');

    useEffect(() => {
        const loadCaptainData = async () => {
            if (captainId) {
                const captain = await getCaptainData(captainId);
                setValue('first_name', captain.first_name);
                setValue('last_name', captain.last_name);
                setValue('patronymic', captain.patronymic);
                setValue('birth_date', captain.birth_date);
                setValue('experience', captain.experience);
                if (captain.image) {
                    setCurrentImageUrl(captain.image);
                }
            }
            setIsLoading(false);
        };

        loadCaptainData().catch(err => console.error('Ошибка загрузки данных капитана:', err));
    }, [captainId, setValue]);

    const onSubmit: SubmitHandler<TypeCaptain> = async (data) => {
        const formData = new FormData();
        formData.append('first_name', data.first_name);
        formData.append('last_name', data.last_name);
        data.patronymic && formData.append('patronymic', data.patronymic);
        formData.append('birth_date', data.birth_date);
        formData.append('experience', data.experience.toString());

        if (data.image && data.image.length > 0) {
            formData.append('image', data.image[0]);
        }

        try {
            if (captainId) {
                await updateCaptain(formData, captainId);
            } else {
                await saveCaptain(formData);
            }
            push('/admin/captains/');

        } catch (error) {
            console.error('Ошибка при сохранении данных капитана:', error);
        }
    };

    if (isLoading) {
        return <CapFerrySkeleton/>;
    }

    return (
        <div className={styles.captainForm}>
            <div className={styles.captainFormWrapper}>
                {currentImageUrl && (
                    <div className={styles.currentImage}>
                        <Image

                            src={currentImageUrl}
                            alt="Текущая картинка капитана"

                            className={styles.currentImagePreview}/>
                    </div>
                )}
                <form onSubmit={handleSubmit(onSubmit)}>
                    <FormInput<TypeCaptain>
                        id="first_name"
                        type="text"
                        name="first_name"
                        label="Имя"
                        kind="none"
                        register={register}
                        rules={{required: "Введите имя капитана"}}
                        errors={errors}
                    />

                    <FormInput<TypeCaptain>
                        id="last_name"
                        type="text"
                        name="last_name"
                        label="Фамилия"
                        kind="none"
                        register={register}
                        rules={{required: "Введите фамилию капитана"}}
                        errors={errors}
                    />

                    <FormInput<TypeCaptain>
                        id="patronymic"
                        type="text"
                        name="patronymic"
                        label="Отчество"
                        kind="none"
                        register={register}
                        rules={{}}
                        errors={errors}
                    />

                    <FormInput<TypeCaptain>
                        id="birth_date"
                        type="date"
                        name="birth_date"
                        label="Дата рождения"
                        kind="none"
                        register={register}
                        rules={{required: "Введите дату рождения капитана"}}
                        errors={errors}
                    />

                    <FormInput<TypeCaptain>
                        id="experience"
                        type="number"
                        name="experience"
                        label="Стаж (лет)"
                        kind="none"
                        min={0}
                        register={register}
                        rules={{required: "Введите стаж капитана"}}
                        errors={errors}
                    />

                    <div className={styles.imageSection}>
                        <label htmlFor="image">Изображение</label>
                        <input type="file" {...register("image", {required: false})} />
                    </div>

                    <Button type="submit" kind="submit" content="Сохранить"/>
                </form>
            </div>
        </div>
    );
}
